<template>
  <div>
    <div id="box"></div>
    <vertical-menu></vertical-menu>
    <div class="tabbar">
      <div id="circle1"></div>
      <div id="circle2"></div>
      <div class="page-header">
        <i class="el-icon-data iconfont"></i>
        <span>Data</span>
      </div>
    </div>
    <div id="base">
      <div class="content">
        <div class="search">
          <div class="row">
            <i class="el-icon-department iconfont"></i>
            <el-select v-model="deSelect" placeholder="select department" @change="departmentChange">
              <el-option label="All Department" :value="0"></el-option>
              <el-option
                v-for="item in department"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <!-- <div class="row">
            <i class="el-icon-manager iconfont"></i>
            <el-select v-model="managerSelect" placeholder="select manager">
              <el-option label="All Manager" :value="0"></el-option>
              <el-option
                v-for="item in managerData"
                :key="item.number"
                :label="item.name"
                :value="item.number">
              </el-option>
            </el-select>
          </div> -->
          <div class="row">
            <el-date-picker
              class="select"
              type="daterange"
              v-model="time"
              range-separator="-"
              start-placeholder="startTime"
              end-placeholder="endTime"
              placeholder="select time range"
              @change="dateChange">
            </el-date-picker>
          </div>
          <div class="row">
            <el-button type="primary">export</el-button>
          </div>
        </div>
        <el-tabs class="tab-view" type="card">
          <el-tab-pane label="Daily">
            <div class="daily-table">
              <el-table
                :data="dailyData"
                :cell-style="{textAlign:'center'}"
                :header-cell-style="{background:'rgba(238, 229, 185,0.4)',textAlign:'center',color:'#606266',fontWeight:'600'}"
                style="width:100%"
                highlight-current-row
                @row-click="showDetail"
                border>
                <el-table-column prop="name" label="Name"></el-table-column>
                <el-table-column prop="role" label="Role" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if="scope.row.role">{{scope.row.role}}</span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column prop="date" label="Date"></el-table-column>
                <el-table-column prop="rosterTime" label="Roster Time"></el-table-column>
                <el-table-column prop="effectiveTime" label="Effective Time"></el-table-column>
                <el-table-column prop="clockIn" label="Clock in">
                  <template slot-scope="scope">
                    <span v-if="scope.row.clockIn">{{scope.row.clockIn}}</span>
                    <span v-else>--:--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="clockOut" label="Clock out">
                  <template slot-scope="scope">
                    <span v-if="scope.row.clockOut">{{scope.row.clockOut}}</span>
                    <span v-else>--:--</span>
                  </template>
                </el-table-column>
                <el-table-column label="Operation">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="showDetail(scope.row)">show</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                class="page"
                background
                @current-change="handleCurrentChange"
                :current-page="page.pageNum"
                :page-size="page.pageSize"
                :page-count="9"
                layout="prev, pager, next"
                :total="page.totalSize">
              </el-pagination>
            </div>
            <div class="show-detail">
              <div class="title">
                Daily clock in record<br>
                within two weeks
              </div>
              <div class="staff-info">
                <i class="el-icon-user iconfont"></i>
                <span>{{clockDetail.name}}</span><br>
                <!-- <i class="el-icon-manager iconfont"></i>
                <span>Dabby</span> -->
                <!-- <el-divider></el-divider> -->
                <i class="el-icon-department iconfont"></i>
                <span>{{clockDetail.departmentName}}</span>
                <i class="el-icon-arrow-down"></i>
              </div>
              <div style="height: 75%">
                <el-scrollbar style="height:100%;">
                  <div class="day-record" v-for="(val, key) in twoWeeks" :key="key">
                    <div class="date">
                      {{changeDay(key)}}
                    </div>
                    <div class="record" v-for="(item, index) in val" :key="index">
                      <span class="role" v-if="item.role != null">{{item.role}}</span><br>
                      <div class="time">
                        <span>{{formatTime(item.clockIn)}}</span>
                      </div>
                      <div class="divide">
                        <span>-</span>
                      </div>
                      <div class="time">
                        <span>{{formatTime(item.clockOut)}}</span>
                      </div>
                      <div style="display: inline-block;">
                        <i class="el-icon-file-editing iconfont" @click="handleClick(item)"></i>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="Period">
            <el-table
              :data="periodData"
              :cell-style="{textAlign:'center'}"
              :header-cell-style="{background:'rgba(238, 229, 185,0.4)',textAlign:'center',color:'#606266',fontWeight:'600'}"
              style="width: 100%"
              border>
              <el-table-column prop="name" label="Name"></el-table-column>
              <el-table-column prop="departmentName" label="Department"></el-table-column>
              <!-- <el-table-column prop="prop" label="Role"></el-table-column> -->
              <el-table-column prop="workinghours" label="Working hours"></el-table-column>
              <el-table-column prop="attendance" label="Attendance"></el-table-column>
              <el-table-column prop="leaveEarly" label="Leave early"></el-table-column>
              <el-table-column prop="late" label="Late"></el-table-column>
              <el-table-column prop="numberOfLeave" label="Number of leave"></el-table-column>
            </el-table>
            <el-pagination
              class="page"
              background
              @current-change="handleCurrentChange2"
              :current-page="page2.pageNum"
              :page-size="page2.pageSize"
              :page-count="11"
              layout="prev, pager, next"
              :total="page2.totalSize">
            </el-pagination>
          </el-tab-pane>
        </el-tabs>
        <el-dialog
          width="30%"
          title="Update Record"
          :visible.sync="editVisible">
          <el-form :model="updateInfo" label-width="100px">
            <el-form-item label="Time" prop="time">
              <el-time-picker
                class="select"
                is-range
                v-model="timeRange"
                range-separator="-"
                start-placeholder="startTime"
                end-placeholder="endTime"
                placeholder="select time range"
                format="HH:mm"
                value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editVisible = false">Cancel</el-button>
            <el-button type="primary" @click="updateRecord">Submit</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import VerticalMenu from '@/components/VerticalMenu.vue'
export default {
  components: {
    VerticalMenu,
  },
  data(){
    return {
      user: {},
      deSelect: 0,
      managerSelect: 0,
      time: [],
      department: [],
      managerData: [],
      dailyData: [],
      periodData: [],
      clockDetail: {},
      record:{
        role: 'Manager Assistant',
        start: '9:00',
        end: '18:30',
      },
      page: {
        totalSize: 2,
        pageNum: 1,
        pageSize: 7
      },
      page2: {
        totalSize: 2,
        pageNum: 1,
        pageSize: 10
      },
      twoWeeks: [],
      recordDate: '',
      editVisible: false,
      timeRange: [],
      updateInfo: {},
    }
  },
  created(){
    this.user = JSON.parse(sessionStorage.getItem('user'));
    this.getWeekday();
    this.getDaily();
    this.getPeriod();
  },
  mounted(){
    this.staffData = JSON.parse(sessionStorage.getItem('staffData'));
    this.managerData = JSON.parse(sessionStorage.getItem('managerData'));
    if(this.staffData === null || this.managerData === null){
      this.getAllStaff();
    }
    this.department = JSON.parse(sessionStorage.getItem('department'));
    if(this.department === null){
      this.getAllDepartment();
    }
  },
  methods: {
    getWeekday() {
      let nowData = new Date();
      let currentDay = nowData.getDay();
      // console.log(_this.weekday);
      //get Sunday
      let sunDayTime = nowData.getTime() - currentDay * 24 * 60 * 60 * 1000;
      //get Saturday
      let satDayTime = nowData.getTime() + (6 - currentDay) * 24 * 60 * 60 * 1000;
      this.time = [sunDayTime, satDayTime]
    },
    departmentChange() {
      this.getDaily();
      this.getPeriod();
    },
    dateChange() {
      this.getDaily();
      this.getPeriod();
    },
    getAllStaff(){
      const _this = this
      _this.$api.staff.getAllStaff().then(res => {
        if (res.data.code === 2000) {
          _this.staffData = res.data.data;
          // _this.sortPosition(_this.staffData)
          sessionStorage.setItem('staffData',JSON.stringify(_this.staffData));
          _this.managerData = _this.staffData.filter((item) => {
            return item.position != 'Staff'
          })
          sessionStorage.setItem('managerData',JSON.stringify(_this.managerData));
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getAllDepartment() {
      const _this = this
      _this.$api.department.getAllDepartment().then(res => {
        if (res.data.code === 2000) {
          _this.department = res.data.data;
          sessionStorage.setItem('department',JSON.stringify(_this.department));
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getDepartManager(index){
      const _this = this;
      _this.$api.department.getManager({
        departmentid: index,
      }).then(res => {
        if(res.data.code === 2000){
          _this.managerData = res.data.data;
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    handleCurrentChange(val) {
      const _this = this;
      _this.page.pageNum = val;
      _this.getDaily();
    },
    handleCurrentChange2(val) {
      const _this = this;
      _this.page2.pageNum = val;
      _this.getPeriod();
    },
    handleClick(val){
      this.editVisible = true;
      this.updateInfo = val;
      if(val.clockOut){
        this.timeRange = [val.clockIn, val.clockOut];
      }else{
        this.timeRange = [val.clockIn, val.clockIn];
      }
    },
    getDaily(){
      const _this = this;
      var departmentId = null;
      var startTime = null;
      var finishTime = null;
      if (this.deSelect != 0){
        departmentId = this.deSelect;
      }
      if (this.time.length != 0){
        startTime = Math.round(new Date(_this.time[0]).valueOf() / 1000);
        finishTime = Math.round(new Date(_this.time[1]).valueOf() / 1000);
      }
      _this.$api.clock.getClock({
        page: _this.page.pageNum,
        rows: _this.page.pageSize,
        departmentId: departmentId,
        number: _this.user.number,
        startTime: startTime,
        finishTime: finishTime,
        paging: true
      }).then(res => {
        if(res.data.code === 2000){
          _this.dailyData = res.data.data.list;
          _this.page.totalSize = res.data.data.total;
        }else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    showDetail(index) {
      const _this = this;
      this.clockDetail = index
      let nowdate = Math.round(new Date().valueOf() / 1000)
      _this.$api.clock.getTwoWeeks({
        unixDate: nowdate,
        number: index.number,
        departmentId: index.departmentId
      }).then(res => {
        if(res.data.code === 2000){
          _this.twoWeeks = res.data.data
          // .map((item) => {
          //   return {
          //     id: item.id,
          //     number: item.number,
          //     clockIn: item.clockIn,
          //     clockOut: item.clockOut,
          //     date: _this.changeDay(item.date),
          //     time: item.date,
          //     uid: item.uid,
          //     role: item.role
          //   }
          // });
          // _this.$forceUpdate();
          console.log(_this.twoWeeks)
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    getPeriod(){
      const _this = this;
      var departmentId = null;
      var startTime = null;
      var finishTime = null;
      if (this.deSelect != 0){
        departmentId = this.deSelect;
      }
      if (this.time.length != 0){
        console.log(_this.time);
        startTime = Math.round(new Date(_this.time[0]).valueOf() / 1000);
        finishTime = Math.round(new Date(_this.time[1]).valueOf() / 1000);
        console.log(startTime);
        console.log(finishTime);
      }
      _this.$api.clock.getPeriod({
        page: _this.page2.pageNum,
        rows: _this.page2.pageSize,
        departmentId: departmentId,
        number: _this.user.number,
        startTime: startTime,
        finishTime: finishTime,
        paging: true
      }).then(res => {
        if(res.data.code === 2000){
          _this.periodData = res.data.data.list;
          _this.page2.totalSize = res.data.data.total;
        }else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
    changeRecord(val){
      this.recordDate = val;
      return true;
    },
    changeDay(date){
      var m=new Array('Jan.','Feb.','Mar.','Apr.','May.','Jun.','Jul','Aug.','Sep.','Oct.','Nov.','Dec');
      var d=new Array("st","nd","rd","th");
      var mn = new Date(date).getMonth();
      var dn = new Date(date).getDate();
      var dns;
      if(((dn%10)<1) || ((dn%10)>3)){
        dns = d[3];
      }else {
        dns=d[(dn%10)-1];
        if((dn==11)||(dn==12)){
          dns=d[3];
        }
      }
      return dn + dns + ' '+ m[mn]
    },
    formatTime(date){
      var date = new Date(date);
      var hh = (date.getHours() + 1 < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
      var mm = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
      return hh + mm;
    },
    updateRecord(){
      const _this = this;
      var clockIn = Math.round(new Date(this.updateInfo.time + ' ' + this.timeRange[0])/1000);
      var clockOut = Math.round(new Date(this.updateInfo.time + ' ' + this.timeRange[1])/1000);
      console.log(clockIn);
      console.log(clockOut);
      console.log(_this.updateInfo);
      _this.$api.clock.updateClock(_this.updateInfo.id, _this.updateInfo.number, {
        clockIn: clockIn,
        clockOut: clockOut
      }).then(res => {
        if(res.data.code === 2000){
          _this.$message.success("update success");
          _this.showDetail(_this.clockDetail);
          _this.editVisible = false;
        } else {
          _this.$message.error(res.data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    }
  }
}
</script>

<style lang="less" scoped>
  #box {
    height: 100%;
    width: 100%;
    position: fixed;
    background-color: #F2F2F2;
    z-index: -1;
  }

  #base {
    padding: 100px 0 0 250px;
  }

  .content {
    padding-bottom: 20px;
    width: 1260px;
    background-color: #F2F2F2;
    float: left;
  }

  #circle1 {
    border-width: 1px;
    position: fixed;
    left: 1318px;
    top: -39px;
    width: 150px;
    height: 150px;
    display: flex;
    border-radius:50%;
    background-color: rgba(253,167,105,0.24);
  }

  #circle2 {
    border-width: 1px;
    position: fixed;
    left: 1418px;
    top: 61px;
    width: 100px;
    height: 100px;
    display: flex;
    border-radius:50%;
    background-color: rgba(150,169,97,0.24);
  }

  .tabbar {
    margin: 0 0 0 250px;
    padding-top: 10px;
    padding-bottom: 10px;
    background-color: #F2F2F2;
    z-index: 100;
    position: fixed;
  }

  .page-header {
    width: 1234px;
    height: 64px;
    background-color: rgba(242,235,211,0.3);
    border: 2px solid rgba(150, 169, 97,0.5);
    border-radius: 5px;
    margin: 0 20px 0 15px;
    line-height: 64px;
    span {
      color: #473C33;
      margin-left: 10px;
      font-size: 30px;
      // font-weight: 600;
    }
    .el-icon-data{
      margin-left: 20px;
      font-size: 35px;
      color: #ABC270;
      // vertical-align: middle;
    }
  }

  .tab-view {
    margin-top: 5px;
    margin-left: 15px;
    width: 1234px;
    position: fixed;
  }

  .search {
    float: right;
    margin-top: 5px;
    position: relative;
    .row {
      display: inline;
      margin-left: 20px;
      position: relative;
      z-index: 101;
    }
    .el-icon-manager, .el-icon-department {
      font-size: 20px;
      margin-right: 5px;
    }
    /deep/ .el-input__inner{
      background-color: rgba(150, 169, 97,0.2);
    }
    /deep/ .el-input__inner::placeholder {
      color: #96A961;
    }
    /deep/ .el-range-editor.el-input__inner {
      width: 300px;
    }
    /deep/ .el-range-input {
      background-color: rgba(150, 169, 97,0);
    }
    /deep/ .el-range-input::placeholder {
      color: #96A961;
    }
    /deep/ .el-select {
      width: 200px;
    }
    /deep/ .el-icon-date{
      color: #000;
    }
  }

  /deep/ .el-tabs--card>.el-tabs__header{
    border-bottom:none;
  }

  /deep/ .el-tabs--card>.el-tabs__header .el-tabs__nav{
    border:none;
  }

  /deep/ .el-tabs__header .el-tabs__item{
    color: #333333;
    background: #d7d7d7;
    width: 100px;
    text-align: center;
    border-radius: 5px 5px 0 0;
    margin-left: 5px;
    margin-right: 5px;
  }

  /deep/ .el-tabs__header .el-tabs__item.is-active{
    border-bottom: none;
    color: #333333;
    background: #c5ceaa;
  }

  /deep/ .el-table--border{
    border: 2px solid rgba(150, 169, 97,0.5);
    border-radius: 5px;
  }

  /deep/ .el-table__empty-block {
    background-color: #F2F2F2;
  }

  /deep/ .el-table tr{
    background-color: #F2F2F2;
  }

  /deep/ .el-table td{
    border: 0px;
    border-top: 1px solid rgba(150, 169, 97,0.5);
  }

  /deep/ .el-table__cell, .el-table__expanded-cell{
    background-color: #F2F2F2;
  }

  /deep/ .el-table__body tr.current-row>td.el-table__cell {
    background-color: #e7ebdf;
  }

  .daily-table {
    width: 80%;
  }

  .page {
    margin-top: 10px;
    float: right;
  }

  .show-detail {
    top: 160px;
    left: 1270px;
    bottom: 20px;
    width: 220px;
    position: fixed;
    background-color: rgba(243,235,211,0.4);
    padding-left: 10px;
    padding-right: 10px;
    padding-top: 10px;
    .title {
      line-height: 25px;
      color: #7C8C4F;
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 10px;
    }
    .staff-info {
      margin-bottom: 5px;
    }
    .staff-info span{
      margin-left: 5px;
      line-height: 25px;
      color: #797979;
      font-size: 15px;
      margin-bottom: 10px;
    }
    .el-icon-user, .el-icon-manager, .el-icon-department, .el-icon-file-editing{
      font-size: 20px;
      color: rgba(246,119,28,0.9);
      margin-bottom: 10px;
    }
    .el-icon-arrow-down {
      // margin-left: 10px;
      float: right;
      margin-top: 5px;
      // vertical-align: text-bottom;
      color: #797979;
      cursor: pointer;
    }
    /deep/ .el-divider--horizontal{
      margin: 10px 0;
      height: 2px;
      background-color: #7C8C4F;
    }
    /deep/ .el-scrollbar__wrap{
      overflow-x: hidden;
    }
  }
  .day-record{
    .date {
      line-height: 20px;
      color: #7C8C4F;
      font-size: 16px;
      font-weight: 600;
      // margin-bottom: 5px;
    }
    .record {
      // text-align: center;
      // line-height: 25px;
      font-size: 16px;
    }
    .role {
      color: rgba(246,119,28,0.65);
    }
    .time {
      width: 70px;
      height: 25px;
      line-height: 25px;
      text-align: center;
      background-color: rgba(150, 169, 97,0.2);
      display: inline-block;
      vertical-align: middle;
      color: #96A961;
      border-radius: 5px;
    }
    .divide {
      line-height: 25px;
      display: inline-block;
      margin: 0 10px;
    }
    .el-icon-file-editing{
      margin-left: 10px;
      cursor: pointer;
    }
  }

  .select {
    width: 250px;
  }
  /deep/ .el-dialog__body{
    // padding-top: 10px;
    // padding-left: 40px;
    padding-bottom: 0px;
  }
</style>
